package com.ddx.controller;

import com.ddx.common.exception.ExceptionUtil;
import com.ddx.common.exception.ResultModel;
import com.ddx.pojo.ShoppingCart;
import com.ddx.service.IShoppingCartService;
import com.ddx.service.IShoppingOrderService;
import com.ddx.service.IShoppingUserCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * 前端首页
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping({"/app"})
public class AjaxController {

    private static Logger logger = LoggerFactory.getLogger(AjaxController.class);

    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IShoppingUserCenterService shoppingUserCenterService;
    @Autowired
    private IShoppingOrderService shoppingOrderService;

    /**
     * 添加购物车商品
     */
    @RequestMapping({"/account/addToCart.do"})
    public @ResponseBody
    Object addToCart(ShoppingCart cart, ModelMap model) {
        logger.debug("添加{}到购物车", cart);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            shoppingCartService.addCart(cart);
            resultModel.setMsg("加入购物车成功！");
        }catch (Exception e){
            logger.error("AjaxController", e);
            ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 购物车商品数量调整
     */
    @RequestMapping({"/account/cartPNumber.do"})
    public @ResponseBody
    Object cartPNumber(ShoppingCart cart, ModelMap model) {
        logger.debug("购物车商品{}调整数量{}", cart.getId(), cart.getProductNumber());
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            shoppingCartService.updateCount(cart);
        }catch (Exception e){
            logger.error("AjaxController", e);
            resultModel= ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 购物车商品删除
     */
    @RequestMapping({"/account/cartDel.do"})
    public @ResponseBody
    Object cartDel(ShoppingCart cart, ModelMap model) {
        logger.debug("购物车商品删除：{}", cart.getId());
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            shoppingCartService.deleteById(cart.getId());
        }catch (Exception e){
            logger.error("AjaxController", e);
            resultModel= ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
}
